/*
 * Copyright (C) 2013 Chen Hui <calmer91@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.harmonyos.fishbun.slice;

import com.harmonyos.fishbun.ImageAdapter;
import com.harmonyos.fishbun.ImageController;
import com.harmonyos.fishbun.ResourceTable;
import com.harmonyos.fishbun.util.Constant;
import com.sangcomz.fishbun.BaseAbilitySlice;
import com.sangcomz.fishbun.FishBun;
import com.sangcomz.fishbun.MimeType;
import com.sangcomz.fishbun.adapter.image.impl.GlideAdapter;
import com.sangcomz.fishbun.util.CommonToolbar;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.ListContainer;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.utils.Color;
import ohos.agp.window.service.WindowManager;
import ohos.event.commonevent.*;
import ohos.global.resource.NotExistException;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.rpc.RemoteException;
import ohos.utils.net.Uri;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

public class WithActivityAbilitySlice extends AbilitySlice {

    private HiLogLabel TAG = new HiLogLabel(HiLog.DEBUG, 0x4321, "WithAbility");

    private int mode = 0;
    private ArrayList<Uri> path = new ArrayList<>();
    private ImageAdapter imageAdapter;
    private EventSubscriber eventSubscriber;
    private Image mShowImg;
    private ListContainer mListContainer;
    private CommonToolbar commonToolbar;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_with_activity);

        initView();
        initData(intent);
        initListener();

    }

    private void initView() {

        WindowManager.getInstance().getTopWindow().get().setStatusBarColor(Color.BLACK.getValue());

        mShowImg = (Image) findComponentById(ResourceTable.Id_img_main);
        mListContainer = (ListContainer) findComponentById(ResourceTable.Id_recyclerview);
        ImageController imageController = new ImageController(mShowImg, this);
        imageAdapter = new ImageAdapter(this, imageController, path);
        mListContainer.setItemProvider(imageAdapter);

        commonToolbar = (CommonToolbar) findComponentById(ResourceTable.Id_with_ability_toolbar);
        commonToolbar.setBackgroundColor(new RgbColor(0,0,0));
        commonToolbar.setTitle("FishBun",Color.WHITE.getValue());
        commonToolbar.setBtnSelectTitle("+",Color.WHITE.getValue());
    }

    private void initData(Intent intent) {
        mode = intent.getIntParam("mode", -1);

        MatchingSkills skills = new MatchingSkills();
        skills.addEvent(Constant.WITH_ACTIVITY_RESULT);
        CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(skills);
        eventSubscriber = new EventSubscriber(subscribeInfo);

        try {
            CommonEventManager.subscribeCommonEvent(eventSubscriber);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private void initListener() {
        commonToolbar.btnSelectTitle.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                switch (mode) {
                    case 0:
                        FishBun.with(getAbility())
                                .setImageAdapter(new GlideAdapter())
                                .setSelectedImages(path)
                                .startAlbum();
                        break;
                    case 1:
                        try {

                            FishBun.with(getAbility())
                                    .setImageAdapter(new GlideAdapter())
                                    .setMaxCount(5)
                                    .setMinCount(3)
                                    .setPickerSpanCount(5)
                                    .setActionBarColor(
                                            Color.getIntColor("#795548"),
                                            Color.getIntColor("#5D4037"),
                                            false
                                    )
                                    .setActionBarTitleColor(Color.getIntColor("#ffffff"))
                                    .setSelectedImages(path)
                                    .setAlbumSpanCount(2, 3)
                                    .setButtonInAlbumActivity(false)
                                    .hasCameraInPickerPage(true)
                                    .exceptMimeType(Arrays.asList(MimeType.GIF))
                                    .setReachLimitAutomaticClose(true)
                                    .setHomeAsUpIndicatorDrawable(
                                            new PixelMapElement(getResourceManager().getResource(ResourceTable.Media_ic_custom_back_white))
                                    )
                                    .setDoneButtonDrawable(
                                            new PixelMapElement(getResourceManager().getResource(ResourceTable.Media_ic_custom_ok))
                                    )
                                    .setAllViewTitle("All")
                                    .setActionBarTitle("FishBun Dark")
                                    .textOnNothingSelected("Please select three or more!")
                                    .startAlbum();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (NotExistException e) {
                            e.printStackTrace();
                        }
                        break;
                    case 2:
                        try {
                            FishBun.with(getAbility())
                                    .setImageAdapter(new GlideAdapter())
                                    .setMaxCount(50)
                                    .setPickerSpanCount(4)
                                    .setActionBarColor(
                                            Color.getIntColor("#ffffff"),
                                            Color.getIntColor("#ffffff"),
                                            true
                                    )
                                    .setActionBarTitleColor(Color.getIntColor("#000000"))
                                    .setSelectedImages(path)
                                    .setAlbumSpanCount(1, 2)
                                    .setButtonInAlbumActivity(true)
                                    .hasCameraInPickerPage(false)
                                    .exceptMimeType(Arrays.asList(MimeType.GIF))
                                    .setReachLimitAutomaticClose(false)
                                    .setHomeAsUpIndicatorDrawable(
                                            new PixelMapElement(getResourceManager().getResource(ResourceTable.Media_ic_arrow_back_black))
                                    )
                                    .setIsUseAllDoneButton(true)
                                    .setMenuDoneText("Choose")
                                    .setMenuAllDoneText("Choose All")
                                    .setIsUseAllDoneButton(true)
                                    .setAllViewTitle("All of your photos")
                                    .setActionBarTitle("FishBun Light")
                                    .textOnImagesSelectionLimitReached("You can't select any more.")
                                    .textOnNothingSelected("I need a photo!")
                                    .startAlbum();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (NotExistException e) {
                            e.printStackTrace();
                        }
                        break;
                    default:
                        terminateAbility();
                        break;
                }
            }
        });

    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    protected void onResult(int requestCode, int resultCode, ArrayList<Uri> resultData) {

        if (requestCode == FishBun.FISHBUN_REQUEST_CODE && resultCode == BaseAbilitySlice.RESULT_OK) {
            if (resultData != null) {
//                ArrayList<Uri> param = resultData;
                this.path = resultData;
                if (path != null && !path.isEmpty()) {
                    imageAdapter.changePath(path);
                }
            }
        }
    }

    class EventSubscriber extends CommonEventSubscriber {

        public EventSubscriber(CommonEventSubscribeInfo info) {
            super(info);
        }

        @Override
        public void onReceiveEvent(CommonEventData commonEventData) {
            Intent intent = commonEventData.getIntent();
            if (intent.getAction().equals(Constant.WITH_ACTIVITY_RESULT)) {
                int requestCode = intent.getIntParam(Constant.REQUEST_CODE, 0);
                int resultCode = intent.getIntParam(Constant.RESULT_CODE, 0);
                ArrayList<String> data = intent.getSerializableParam(Constant.RESULT_DATA);
                ArrayList<Uri> resultData = new ArrayList<>();
                if (data != null) {
                    for (String str : data) {
                        resultData.add(Uri.parse(str));
                    }
                }
                onResult(requestCode, resultCode, resultData);
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        try {
            CommonEventManager.unsubscribeCommonEvent(eventSubscriber);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}
